package com.hyst.seviceImpl;

import com.hyst.common.Contants;
import com.hyst.common.ResultBean;
import com.hyst.domain.Admin;
import com.hyst.service.AdminService;
import com.hyst.service.LoginService;
import com.hyst.utils.CookieUtil;
import com.hyst.utils.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AdminService adminService;

    /**
     * 登录
     */
    @Override
    public ResultBean login(String username, String password, HttpServletRequest request,HttpServletResponse response) {
        try {
            Admin admin = adminService.getAdmin(username);
            if (admin == null) {
                return ResultBean.fail("账户不存在");
            }

            if (!password.equals(admin.getPassword())) {
                return ResultBean.fail("密码不正确");
            }
            putUserToSession(admin, password,request, response);
            Map<String,String> result = new HashMap<>();
            result.put("return_to", "/");
            return ResultBean.success(result);
        } catch (Exception e) {
            System.out.println(e);
        }
        return ResultBean.fail("登录异常");
    }


    private void putUserToSession(Admin admin, String password,HttpServletRequest request, HttpServletResponse response) {
        request.getSession().setAttribute(Contants.SESSION_USER_INFO, admin);
        // 做登录
        String sessionId = request.getSession().getId();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        CookieUtil.setCookie(response, Contants.SESSION_NAME, sessionId, CookieUtil.COOKIE_MAX_AGE, "");
        CookieUtil.setCookie(response, Contants.COOKIE_LOGIN_NAME, admin.getEmail(), CookieUtil.COOKIE_MAX_AGE, "");
        CookieUtil.setCookie(response, Contants.COOKIE_LOGIN_PWD, password, CookieUtil.COOKIE_MAX_AGE, "");
    }
}
